/*
 * Copyright 2014 Will Dignazio
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <socketio.h>
#include "internal.h"

/* Acknowledge the authorization, form a session */
int
acknowledge(SocketData *sdata, SocketSession *session)
{
	char *acktok;
	char *sidptr;
	char *sidr;
	char *saveptr;
	uint32_t sidsz;
	uint32_t heart_to;
	uint32_t close_to;
	uint32_t transtypes;
	int ret;

	transtypes = 0;
	acktok = NULL;
	sidptr = NULL;
	sidr  = NULL;
	saveptr = NULL;
	sidsz = 0;
	heart_to = 0;
	close_to = 0;
	ret = 0;

	sidr = strchr(sdata->cdata, ':');
	sidsz = sidr - sdata->cdata;

	sidptr = malloc(sidsz);
	memcpy(sidptr, sdata->cdata, sidsz);

	acktok = strtok_r(sidr, ":", &saveptr);
	heart_to = atoi(acktok);

	acktok = strtok_r(NULL, ":", &saveptr);
	close_to = atoi(acktok);

	for(acktok = strtok_r(NULL, ",", &saveptr); acktok != NULL;
			      acktok = strtok_r(NULL, ",", &saveptr)) {
		    if(strcmp("xhr-polling", acktok) == 0)
			    transtypes |= TRANS_XHR_POLLING;
		    if(strcmp("xhr-multipart", acktok) == 0)
			    transtypes |= TRANS_XHR_MULTIPART;
		    if(strcmp("htmlfile", acktok) == 0)
			    transtypes |= TRANS_HTMLFILE;
		    if(strcmp("websocket", acktok) == 0)
			    transtypes |= TRANS_WEBSOCKET;
		    if(strcmp("flashsocket", acktok) == 0)
			    transtypes |= TRANS_FLASHPOCKET;
		    if(strcmp("jsonp-polling", acktok) == 0)
			    transtypes |= TRANS_JSONP_POLLING;
	}

	ret = startsession(sidptr, heart_to, close_to, transtypes, session);

	free(sidptr);
	return ret;
}

/* Handshake information with socket */
int
handshake(SocketData *sdata, SocketSession *session)
{
	SocketRequest *req;
	int ret;

	ret = -1;

	/* Specific configuration for handshaking */
	req = allocrequest(PROTO_HTTP, sdata->cdata, "socket.io", 1, 0, 0, "");
	if(req == NULL)
		goto fail;
	
	/*
	 * Normally this would be used for asynchronous request
	 * posts to the server, however here we're manually
	 * blocking until it finished so that we can get get
	 * session information.
	 */
	ret = postrequest(req, session, acknowledge);
	if(ret != 200) {
		ret = -1;
		goto fail;
	}

	ret = 0;
fail:
	freerequest(req);
	return ret;
}
